<?php

namespace app\common\model;

use app\common\constants\DBConstant;
use app\common\util\CommonUtil;

/**
 * 房屋
 */
class House extends BaseModel
{

    // 表名,不含前缀
    protected $name = 'house';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    /**
     * @var Layout
     */
    private $layoutModel;

    /**
     * @var Infrastructure
     */
    private $infrastructureModel;

    /**
     * @var Orientation
     */
    private $orientationModel;

    /**
     * @var SubwayLine
     */
    private $subwayLineModel;

    /**
     * @var Tag
     */
    private $tagModel;

    /**
     * @var Attachment
     */
    private $attachmentModel;

    /**
     * @var Region
     */
    private $regionModel;

    /**
     * @var HouseType
     */
    private $houseTypeModel;

    /**
     * @var Config
     */
    private $configModel;

    public function type()
    {
        return $this->belongsTo('HouseType', 'type_id')->setEagerlyType(0);
    }

    public function layout()
    {
        return $this->belongsTo('Layout', 'layout_id')->setEagerlyType(0);
    }

    public function region()
    {
        return $this->belongsTo('Region', 'region_id')->setEagerlyType(0);
    }

    public function orientation()
    {
        return $this->belongsTo('Orientation', 'orientation_id')->setEagerlyType(0);
    }


    public function initialize()
    {
        parent::initialize();
        $this->regionModel = new Region();
        $this->layoutModel = new Layout();
        $this->infrastructureModel = new Infrastructure();
        $this->orientationModel = new Orientation();
        $this->subwayLineModel = new SubwayLine();
        $this->tagModel = new Tag();
        $this->attachmentModel = new Attachment();
        $this->houseTypeModel = new HouseType();
        $this->configModel = new Config();
    }


    private function _decodeData($houseData)
    {
//        $houseData['discountAmount'] = $houseData['amount'] * $houseData['discount_rate'];
        //  修改逻辑,前端直接输入折扣价
        $houseData['discountAmount'] = $houseData['discount_rate'];

        $houseData['photos'] = CommonUtil::splitArr($houseData['photos'], DBConstant::TABLE_FIELD_JOIN_SYMBOL);
        $tempPhotos = $this->attachmentModel->whereIn("id", $houseData['photos'])->field(['id', 'url'])->select()->toArray();
        $houseData['photoList'] = [];
        foreach ($tempPhotos as $key => $value) {
            $tempPhotos[$key]['url'] = CommonUtil::formatHostUrl($value['url']);
        }
        $houseData['photoList'] = $tempPhotos;

        $houseData['tags'] = CommonUtil::splitArr($houseData['tags'], DBConstant::TABLE_FIELD_JOIN_SYMBOL);
        $houseData['tagList'] = $this->tagModel->whereIn("id", $houseData['tags'])->select()->toArray();

        $houseData['infrastructure_id'] = CommonUtil::splitArr($houseData['infrastructure_id'], DBConstant::TABLE_FIELD_JOIN_SYMBOL);
        $tmp = [];
        foreach ($houseData['infrastructure_id'] as $key => $value) {
            $tmp[] = $this->infrastructureModel->selectById($value, true);
        }
        $houseData['infrastructureList'] = $tmp;

        $houseData['subway_line_id'] = CommonUtil::splitArr($houseData['subway_line_id'], DBConstant::TABLE_FIELD_JOIN_SYMBOL);
        $houseData['subwayLineList'] = $this->subwayLineModel->whereIn("id", $houseData['subway_line_id'])->select()->toArray();

        $houseData['orientation'] = $this->orientationModel->where("id", $houseData['orientation_id'])->find();
        $houseData['layout'] = $this->layoutModel->where("id", $houseData['layout_id'])->find();
        $houseData['region'] = $this->regionModel->where("id", $houseData['region_id'])->find();
        $houseData['houseType'] = $this->houseTypeModel->where("id", $houseData['type_id'])->find();

        $houseData['paymentDesc'] = $this->configModel->findById(1);
        return $houseData;
    }

    /**
     * 查询所有关联的数据
     * @param $id
     * @param $isAll
     * @return array
     */
    public function selectById($id, $isAll)
    {
        $findData = $this->get($id);
        if (empty($findData)) return [];
        if ($isAll === false) return $findData;
        return $this->_decodeData($findData);
    }

    public function getIndexData($requestData)
    {
        $query = $this->where("status", 1);
        if (!empty($requestData['startPrice'])) {
            $query->where("amount", ">=", $requestData['startPrice']);
        }
        if (!empty($requestData['endPrice'])) {
            $query->where("amount", "<=", $requestData['endPrice']);
        }
        if (!empty($requestData['startArea'])) {
            $query->where("area", ">=", $requestData['startArea']);
        }
        if (!empty($requestData['endArea'])) {
            $query->where("area", "<=", $requestData['endArea']);
        }
        if (!empty($requestData["search_text"])) $query->where("title", "like", "%" . $requestData["search_text"] . "%");
        if (!empty($requestData['region_id'])) $query->where("region_id", $requestData["region_id"]);
        if (!empty($requestData['subway_line_id'])) $query->whereLike("subway_line_id", "%," . $requestData["subway_line_id"] . ",%");
        if (!empty($requestData['layout_id'])) $query->where("layout_id", $requestData["layout_id"]);
        if (!empty($requestData['orientation_id'])) $query->where("orientation_id", $requestData["orientation_id"]);
        if (!empty($requestData["order"])) {
            switch ($requestData["order"]) {
                case "new":
                    $query->order("create_time", "desc");
                    break;
                case "price_min":
                    $query->order("amount", "asc");
                    break;
                case "price_max":
                    $query->order("amount", "desc");
                    break;
                case "area_min":
                    $query->order("area", "asc");
                    break;
                case "area_max":
                    $query->order("area", "desc");
                    break;
            }
        }

        $page = 1;
        $limit = 20;
        if (!empty($requestData['page'])) $page = $requestData['page'];
        $query->page($page, $limit);
        $houseList = $query->select()->toArray();
        foreach ($houseList as $key => $value) {
            $houseList[$key] = $this->_decodeData($value);
        }
        return $houseList;
    }

    public function searchHouseByMap($lng, $lat, $distance)
    {
        $houseList = $this->query("select h.*,st_distance_sphere(point(h.longitude,h.latitude),point (:lng,:lat)) as distance from `house` as h where h.status = 1 and  st_distance_sphere(point(h.longitude,h.latitude),point (:lng2, :lat2)) <=:distance order by distance desc", [
            "lng" => $lng,
            "lat" => $lat,
            "lng2" => $lng,
            "lat2" => $lat,
            "distance" => $distance
        ]);
        foreach ($houseList as $key => $value) {
            $houseList[$key] = $this->_decodeData($value);
        }
        return $houseList;
    }

    public function getHousePassword()
    {

    }

    public function getStatusList()
    {
        return [
            [
                'id' => 1,
                'title' => '出租中'
            ],
            [
                'id' => 2,
                'title' => '已签约'
            ],
            [
                'id' => 3,
                'title' => '审核中'
            ],
            [
                'id' => 4,
                'title' => '已下线'
            ],
        ];
    }

}
